package de.jkoslows.decisions.control;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import de.jkoslows.decisions.entity.Type;
import de.jkoslows.decisions.entity.Unit;

public class Types {

	public static final Type empty = new Type("empty");
	
	public static final Unit emptyUnit = new Unit("unit");
	
	private static Map<Type, Unit> types = new HashMap<Type, Unit>();
	
	private static  Set<Unit> units = new HashSet<Unit>();

	public static Type getType(String typeId) {
		synchronized (types) {
			return add(new Type(typeId));

		}
	}
	
	public static Type getType(String typeId, String unitId) {
		synchronized (types) {
			return add(new Type(typeId), createUnit(unitId));

		}
	}
	
	public static Collection<Type> getTypes(){
		synchronized (types) {
			return new HashSet<Type>(types.keySet());			
		}
	}

	private static Type add(Type type) {
		if (types.keySet().contains(type))
			return type;
		add(type, emptyUnit);
		return type;
	}
	
	private static Type add(Type type, Unit unit) {
		if (types.keySet().contains(type)){
			Unit mappedUnit = types.get(type);
			if(!mappedUnit.equals(unit))
				throw new IllegalArgumentException("Type "+type +" is already mapped to unit "+mappedUnit);
			return type;
		}
		types.put(type, unit);
		return type;
	}

	public static Unit getUnit(Type type) {
		synchronized (types) {
			return types.get(type);			
		}
	}
	
	public static Collection<Unit> getUnits(){
		synchronized (units) {
			return new HashSet<Unit>(units);			
		}
		
	}
	
	public static Unit createUnit(String unitId){
		synchronized (units) {
			Unit unit = new Unit(unitId);
			units.add(unit);
			return unit;			
		}
	}

}
